import { BadRequestException, Injectable } from '@nestjs/common';
import { CreateMeetingRoomDto } from './dto/create-meeting-room.dto';
import { UpdateMeetingRoomDto } from './dto/update-meeting-room.dto';
import { InjectEntityManager, InjectRepository } from '@nestjs/typeorm';
import { MeetingRoom } from './entities/meeting-room.entity';
import { EntityManager, Like, Repository } from 'typeorm';

@Injectable()
export class MeetingRoomService {
  @InjectRepository(MeetingRoom)
  private meetingRoomRepository: Repository<MeetingRoom>;

  @InjectEntityManager()
  private entityManager: EntityManager;

  async find(
    pageNo: number,
    pageSize: number,
    name: string,
    capacity: number,
    equipment: string,
  ) {
    if (pageNo < 1) {
      throw new BadRequestException('pageNo 不能小于1');
    }
    const skipCount = (pageNo - 1) * pageSize;

    const condition: Record<string, any> = {};

    if (name) {
      condition.name = Like(`%${name}%`);
    }

    if (capacity) {
      condition.capacity = capacity;
    }

    if (equipment) {
      condition.equipment = Like(`%${equipment}%`);
    }

    const [meetingRooms, total] = await this.meetingRoomRepository.findAndCount(
      {
        skip: skipCount,
        take: pageSize,
        where: condition,
      },
    );
    return { meetingRooms, total };
  }

  async create(createMeetingRoomDto: CreateMeetingRoomDto) {
    const room = await this.meetingRoomRepository.findOneBy({
      name: createMeetingRoomDto.name,
    });

    if (room) {
      throw new BadRequestException('会议室名字已存在');
    }

    return this.meetingRoomRepository.save(createMeetingRoomDto);
  }

  async update(updateMeetingRoomDto: UpdateMeetingRoomDto) {
    const room = await this.meetingRoomRepository.findOneBy({
      id: updateMeetingRoomDto.id,
    });
    if (!room) {
      throw new BadRequestException('会议室不存在');
    }

    room.name = updateMeetingRoomDto.name || '';
    room.capacity = updateMeetingRoomDto.capacity || 0;
    room.location = updateMeetingRoomDto.location || '';
    if (updateMeetingRoomDto.equipment) {
      room.equipment = updateMeetingRoomDto.equipment;
    }
    if (updateMeetingRoomDto.description) {
      room.description = updateMeetingRoomDto.description;
    }

    await this.meetingRoomRepository.update(
      {
        id: updateMeetingRoomDto.id,
      },
      room,
    );
    return 'success';
  }

  async findById(id: number) {
    const room = await this.meetingRoomRepository.findOneBy({
      id,
    });

    if (!room) {
      throw new BadRequestException('会议室不存在');
    }

    return room;
  }

  async delete(id: number) {
    // 先删除相关预定
    // const bookings = await this.entityManager.findBy(Booking, {
    //   room: {
    //     id,
    //   },
    // });
    // for (let i = 0; i < bookings.length; i++) {
    //   await this.entityManager.delete(Booking, bookings[i].id);
    // }

    await this.meetingRoomRepository.delete(id);
    return 'success';
  }
}
